package xyz.yeidi.utils;

import xyz.yeidi.config.JDBCConfig;

import java.sql.*;

/**
 * @Author JIP
 * @Date 2021-07-29 9:35
 * @Version 1.0
 * @Describe :
 */
public class ConnUtils {
    private static final ThreadLocal<Connection> TL = new ThreadLocal<Connection>();
    static{
        try {
            Class.forName(JDBCConfig.DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //创建连接
    public static Connection createConnection(){
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(JDBCConfig.URL,JDBCConfig.USERNAME, JDBCConfig.PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    //得到连接
    public static Connection getConnection(){
        Connection con = null;
        con = TL.get();
        if (con==null) {
            con = createConnection();
            TL.set(con);
        }
        return con;
    }

    //关闭连接
    public static void close() {
        Connection con = TL.get();
        try {
            if (con != null) {
                con.close();
            }
            //至关重要，否则容易造成内存溢出等问题。
            TL.remove();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //关闭资源
    public static void close(ResultSet rs, Statement statement){
        try {
            if(rs!=null){
                rs.close();
            }
            if(statement!=null){
                statement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //关闭资源
    public static void close(Statement statement){
        try {
            if(statement!=null){
                statement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
